class Solution {
public:
    int candy(vector<int>& ratings) {
        int n = ratings.size(), result = 0;
        vector<int> left_prev(n), right_prev(n);

        for (int i = 1; i < n; i++) {
            if (ratings[i - 1] < ratings[i]) 
                left_prev[i] = left_prev[i - 1] + 1;
            else 
                left_prev[i] = 0;
        }

        for (int i = n - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1]) 
                right_prev[i] = right_prev[i + 1] + 1;
            else 
                right_prev[i] = 0;
        }

        for (int i = 0; i < n; i++) {
            result += max(left_prev[i], right_prev[i]) + 1;
        }
        return result;
    }
};
